package com.ls.guava;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.RemovalListener;
import com.ls.mq.util.Toolkit;


public class CacheFactory {

	
	/**
	 * 
	 * @param access 多久未使用缓存数据则删除 单位秒
	 * @param expire
	 *            缓存超时时间 单位秒
	 * @param listenter
	 *            缓存项移除时的监听者
	 * @return
	 */
	public static <K, V> Cache<K, V> cached(Long access, Long expire, RemovalListener<K, V> listenter) {
		return cached(null, access, expire, null, listenter);
	}

	/**
	 * 
	 * @param expire
	 *            缓存超时时间 单位秒
	 * @param listenter
	 *            缓存项移除时的监听者
	 * @return
	 */
	public static <K, V> Cache<K, V> cached(Long expire, RemovalListener<K, V> listenter) {
		return cached(null, null, expire, null, listenter);
	}

	/**
	 * 
	 * @param maxSize
	 *            缓存最大个数
	 * @param access
	 *            多久未使用则删除缓存 单位 second
	 * @param expire
	 *            超期时间 单位 second
	 * @param cacheLoader
	 *            缓存不存在时如何加载
	 * @param listenter
	 *            缓存项移除时的监听者
	 * @return
	 */
	 @SuppressWarnings("unchecked")
		public static <K, V> Cache<K, V> cached(Long maxSize, Long access, Long expire,
				CacheLoader<K, V> cacheLoader, RemovalListener<K, V> listenter) {
			Cache<K, V> cache = null;
			CacheBuilder<K, V> builder = (CacheBuilder<K, V>) CacheBuilder.newBuilder();
			if (Toolkit.notEmpty(maxSize) && maxSize > 0)
				builder = builder.maximumSize(maxSize);
			if (Toolkit.notEmpty(access) && access > 0)
				builder = builder.expireAfterAccess(access, TimeUnit.SECONDS);
			if (Toolkit.notEmpty(expire) && expire > 0)
				builder = builder.expireAfterWrite(expire, TimeUnit.SECONDS);
			if (Toolkit.notEmpty(listenter))
				builder = builder.removalListener(listenter);
			if (Toolkit.notEmpty(cacheLoader))
				cache = builder.build(cacheLoader);
			else
				cache = builder.build();
			return cache;
		}
}
